# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.


from tkinter import *
from windnd import hook_dropfiles
from tkinter.messagebox import showinfo
from PIL import Image, ImageDraw, ImageFont, ImageSequence
from os import path
from datetime import datetime  # 引入datetime模块


def dragged_files(files):
    text = en.get()
    file = '\n'.join((item.decode('gbk') for item in files))
    # showinfo('您拖放的文件', file)
    dir_name, full_file_name = path.split(file)
    file_name = path.splitext(full_file_name)[0]
    sufix = path.splitext(full_file_name)[1][1:]
    print(file_name, sufix)
    if sufix == 'jpg' or sufix == 'JPG' or sufix == 'png' or sufix == 'PNG':
        img = Image.open(file)
        img_after = add_text_to_image(img, text)
        time_str = datetime.now().strftime('%Y_%m_%d_%H_%M_%S')  # 获取当前时间并转化成字符串
        print(file_name)
        img_after.save(file_name + '_水印' + '.png')
        showinfo('Success !', '静态图转换成功！')

    elif sufix == 'GIF' or sufix == 'gif':
        watermark_on_gif(file, text, file_name)
        showinfo('Success !', 'GIF 转换成功！')

    else:
        showinfo('Error !', '您拖入的文件不是jpg、jpg、gif文件！')


def add_text_to_image(image, text):
    font_size = 32
    font = ImageFont.truetype('C:\Windows\Fonts\STHUPO.TTF', font_size)  # 加载字体对象
    # 添加背景
    new_img = Image.new('RGBA', (image.size[0] * 3, image.size[1] * 3), (0, 0, 0, 0))
    new_img.paste(image, image.size)
    # 添加水印
    font_len = len(text)
    hex_len = int(len(text.encode('gb2312')) / 2)
    print(font_len)
    print(hex_len)
    rgba_image = new_img.convert('RGBA')
    text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0))
    draw = ImageDraw.Draw(text_overlay)

    for i in range(0, rgba_image.size[0], hex_len * font_size + font_size * 2):
        for j in range(0, rgba_image.size[1], font_size*2):
            draw.text((i, j), text, font=font, fill=(0, 0, 0, 60))
    text_overlay = text_overlay.rotate(-45)
    image_with_text = Image.alpha_composite(rgba_image, text_overlay)

    # 裁切图片
    image_with_text = image_with_text.crop((image.size[0], image.size[1], image.size[0] * 2, image.size[1] * 2))
    return image_with_text


def watermark_on_gif(in_gif, text, file_name):
    """本函数给gif动图加水印"""
    frames = []
    font_size = 32
    font = ImageFont.truetype('C:\Windows\Fonts\STHUPO.TTF', font_size)  # 加载字体对象
    font_len = len(text)
    hex_len = int(len(text.encode('gb2312')) / 2)
    print(font_len)
    print(hex_len)
    gif = Image.open(in_gif)  # 打开gif图形
    water_im = gif.convert('RGBA')  # 新建RGBA模式的水印图
    text_overlay = Image.new('RGBA', water_im.size, (255, 255, 255, 0))
    draw = ImageDraw.Draw(text_overlay)  # 新建绘画层
    for i in range(-100, text_overlay.size[0] + 100, hex_len * font_size + font_size * 2):
        for j in range(-100, text_overlay.size[1] + 100, font_size*2):
            draw.text((i, j), text, font=font, fill=(0, 0, 0, 60))
    text_overlay = text_overlay.rotate(-45)
    for frame in ImageSequence.Iterator(gif):  # 迭代每一帧
        frame = frame.convert("RGBA")  # 转换成RGBA模式
        frame = Image.alpha_composite(frame, text_overlay)  # 把水印粘贴到frame
        # frame = frame.crop((gif.size[0], gif.size[1], gif.size[0] * 2, gif.size[1] * 2))
        frames.append(frame)  # 加到列表中
    newgif = frames[0]  # 第一帧
    # quality参数为质量，duration为每幅图像播放的毫秒时间
    # out_gif = datetime.now().strftime('%Y_%m_%d_%H_%M_%S') + '.gif'
    out_gif = file_name + '_水印' + '.gif'
    newgif.save(out_gif, save_all=True, append_images=frames[1:], quality=85, duration=100)


if __name__ == '__main__':
    # 定义Tkinter
    tk = Tk()
    tk.wm_title('图片水印生成 v2.4')
    tk.geometry('300x200')
    Label(tk, text='请把图片文件拖拽至此\n目前仅支持JPG、PNG、GIF格式\n水印图片将生成在本程序所在文件夹\n\n版权所有：瓜哥\n邮箱: cswcswcsw2008@qq.com').pack(
        side=TOP,
        expand=YES,
        fill=BOTH)
    Label(tk, text='水印文字：').pack(side=LEFT)
    en = Entry(tk)
    en.pack(side=RIGHT, expand=YES, fill=X)
    en.insert(0, 'CAE Result Preview')
    # tk.iconbitmap('melon.ico')
    txt = en.get()
    hook_dropfiles(tk, func=dragged_files)
    tk.mainloop()
